﻿using AixRegisterInfodll;
using FinalTestMachine.Connect;
using FinalTestMachine.Funs;
using FinalTestMachine.Motion.Aixs;
using FinalTestMachine.Motion.IO;
using FinalTestMachine.Motion.Process.SubProcess;
using FinalTestMachine.View.MainUnits;
using RM_dll2;
using RM_dll2.Process;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
using WpfZMotion_AAControl.Core.Tools;

namespace FinalTestMachine.Motion.Process
{
    /// <summary>
    /// 机器复位
    /// </summary>
    internal class Process_ResMachine : RM_dll2.Process.ProcessResMachineBase
    {
        public static readonly Process_ResMachine Cur = new Process_ResMachine();

        private Process_ResMachine() : base("机器复位", StaticInitial.Motion, true)
        {
        }

        private bool IsStop = false;

        public override void Stop()
        {
            base.Stop();
            IsStop = true;
        }

        public event Action ClearErrInfo;

        public void Clear()
        {
            ClearErrInfo?.Invoke();
        }

        protected override ProcessResMachineArgs ImplementImplementRunAction()
        {
            WriteToUser("进入复位流程");
            ProcessResMachineArgs args = new ProcessResMachineArgs();
            IsStop = false;

            try
            {
                WriteToUser("复位所有输出点和气缸");
                StaticIOHelper.ResInitial();
                Sleep(100);
                Ref_Step("开始复位电机");

                if (!StaticIOHelper.In_Safe_Checked.In())
                {
                    WriteErrToUser("光栅被遮挡，无反馈！复位退出！");
                    return args;
                }
               
                CheckActionHelper checkAction = new CheckActionHelper();
                SubprocessUnloadNGProduct.Cur.IsWaitNGProductUnload = false;

                bool IsHomeOk = true;
                bool isrecord = true;
                while (Motion.CurOrder.IsResing)
                {
                    if (IsStop)
                    {
                        IsStop = false;
                        break;
                    }
                    void StopAxis(AixCreateBase aixCreateBase)
                    {
                        if (Math.Abs(aixCreateBase.GetCmdPos() - aixCreateBase.GetEncPos()) > 15)
                        {
                            //aixCreateBase.StopSlowDown();
                            //WriteErrToUser($"当前{aixCreateBase.Name}反馈脉冲和输出脉冲相差大于15");
                        }
                        Sleep(200);
                    }

                    switch (Step)
                    {
                        case "开始复位电机":
                            Task.Run(()=> {
                                while (isrecord)
                                {
                                    StopAxis(Aixs.Site6.Aix_Site6_PipeUpDown.Cur);
                                    StopAxis(Aixs.Site2.Aix_Site2_PlaneSourceLift.Cur);
                                    StopAxis(Aixs.Site4.Aix_Site4_PlaneSourceLift.Cur);
                                    StopAxis(Aixs.Site4.Aix_Site4_RelayMirror.Cur);
                                    StopAxis(Aixs.Site2.Aix_Site2_RelayMirror.Cur);
                                }
                            });

                            //三四五站位最高位置的轴先回原
                            Parallel.Invoke(
                                Aixs.Site2.Aix_Site2_PlaneSourceLift.Cur.Home,
                                Aixs.Site6.Aix_Site6_PipeUpDown.Cur.Home,
                                Aixs.Site4.Aix_Site4_PlaneSourceLift.Cur.Home
                               );

                            Parallel.Invoke(
                                Aixs.Site2.Aix_Site2_PlaneSourceLift.Cur.WaitPos.Mov,
                                Aixs.Site6.Aix_Site6_PipeUpDown.Cur.WaitPos.Mov,
                                Aixs.Site4.Aix_Site4_PlaneSourceLift.Cur.WaitPos.Mov
                               );

                            //第二工位轴再回原
                            Parallel.Invoke(
                                Aixs.Site2.Aix_Site2_RelayMirror.Cur.Home,
                                Aixs.Site4.Aix_Site4_RelayMirror.Cur.Home
                                );

                            Parallel.Invoke(
                                Aixs.Site2.Aix_Site2_RelayMirror.Cur.WaitPos.Mov,
                                Aixs.Site4.Aix_Site4_RelayMirror.Cur.WaitPos.Mov
                                );

                            isrecord = false;

                            Ref_Step("开始复位主轴");
                            break;

                        case "开始复位主轴":
                            Aixs.Aix_Turn.Cur.Home();
                            //复位光管轴
                            Ref_Step("判断每个轴是否复位成功");
                            break;

                        case "判断每个轴是否复位成功":
                            foreach (var item in StaticAixInfoRegisterManager.aixRegisterInfo.CheckAixIsHomeOK)
                            {
                                if (item.Name.StartsWith("光管"))
                                {
                                    if (!Funs.FunLightPipeSettings.Cur.CheckCurrentLighgPiPeCanUse(item.Name))
                                        continue;
                                }
                                if (item.GetIsBusy())
                                {
                                    WriteToUser($"{item.Name} 回原点未完成,开始进入等待...", Brushes.Red, false);
                                    if (checkAction.CheckAction(() => item.GetIsBusy() == false, 5000))
                                    {
                                        if (item.GetIsHomeOK())
                                        {
                                            WriteToUser($"{item.Name} 回原点完成...", Brushes.White, false);
                                        }
                                        else
                                        {
                                            IsHomeOk = false;
                                            WriteToUser($"{item.Name} 回原点失败！", Brushes.Red, false);
                                        }
                                    }
                                }
                                else
                                {
                                    if (item.GetIsHomeOK())
                                    {
                                        WriteToUser($"{item.Name} 回原点完成...", Brushes.White, false);
                                    }
                                    else
                                    {
                                        IsHomeOk = false;
                                        WriteToUser($"{item.Name} 回原点失败", Brushes.Red, false);
                                    }
                                }
                            }

                            if (IsHomeOk)
                            {
                                WriteToUser("所有轴已复位成功...", Brushes.White, false);
                                Ref_Step("光管进行回原");
                            }
                            else
                            {
                                throw new Exception("复位失败：存在轴未能复位成功!");
                            }

                            
                            break;

                        case "光管进行回原":
                            if (PipeController.Cur.AllHome())
                            {
                                WriteToUser("光管回原成功！");
                            }
                            else
                            {
                                throw new Exception("光管回原失败！");
                            }
                            

                            Ref_Step("光管移动到等待位");
                            break;

                        case "光管移动到等待位":
                            PipeController.Cur.AllWait();
                            try
                            {
                                if (IsStop == false)
                                {
                                    Aixs.Aix_Turn.Cur.Mov_0();
                                }
                                args.IsResOK = true;

                                if (Funs.FunCommSelection.Cur.IsUseSocketSNCheck)
                                {
                                    WriteToUser("Socket验证被启用");
                                    Ref_Step("Socket验证");
                                }
                                else
                                {
                                    Ref_Step("退出");
                                }
                                break;
                            }
                            catch (Exception ex)
                            {
                                WriteErrToUser(ex.Message);
                                break;
                            }

                        case "Socket验证":
                            CheckSocketSN();
                            Ref_Step("退出");
                            break;

                        case "退出":
                            Clear();
                            args.IsExitOK = true;
                            IsStop = true;
                            WriteToUser("Res OK...", Brushes.Green, true);
                            break;
                    }

                    Sleep(10);
                }
            }
            catch (Exception ex)
            {
                args.IsExitOK = false;
                IsStop = true;
                WriteErrToUser($"设备复位失败:{ex.Message}");
                WriteErrToUser($"{Name}出现异常，异常信息详细信息:{AM.Tools.ExceptionHelper.GetInnerExceptionMessage(ex)}");
            }
            return args;
        }

        private void CheckSocketSN()
        {
            if (SocketSNSetting.Cur.SocketList.Count == 0)
            {
                throw new Exception("未设置SocketSN对应表!");
            }
            if (SocketSNSetting.Cur.SocketList.Count != GlobalParams.WorkstationSum)
            {
                throw new Exception($"设置SocketSN对应表不等于{GlobalParams.WorkstationSum}!");
            }

            for (int i = 0; i < GlobalParams.WorkstationSum; i++)
            {
                SocketSNSetting.Cur.SN = "";
                StaticIOHelper.Out_SocketScanTrigger.Out_OFF();
                Sleep(100);
                StaticIOHelper.Out_SocketScanTrigger.Out_ON();
                Sleep(50);
                int timeout = 300;

                foreach (var item in SocketSNSetting.Cur.SocketList)
                {
                    if (RotatedMovNextHelper.tagPos[0] == item.ID)
                    {
                        timeout = 300;
                        while (timeout-- > 0 && SocketSNSetting.Cur.SN != item.SN)
                        {
                            Sleep(10);
                        }
                        if (timeout <= 0)
                        {
                           StaticIOHelper.Out_SocketScanTrigger.Out_OFF();
                            throw new Exception("socket验证失败");
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                StaticIOHelper.Out_SocketScanTrigger.Out_OFF();
                RotatedMovNextHelper.MovNext();
            }
        }
    }
}